package com.keruyun.base.lock;

import org.springframework.data.redis.core.RedisTemplate;

import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.AbstractQueuedSynchronizer;

/**
 * Created by shynin on 18-4-25.
 */
public class SynchronizedQueueRedis extends AbstractQueuedSynchronizer {

    private String lockKey;
    private RedisTemplate redisTemplate;

    SynchronizedQueueRedis(String lockKey, RedisTemplate redisTemplate) {
        this.lockKey = lockKey;
        this.redisTemplate = redisTemplate;
    }
    @Override
    protected boolean tryAcquire(int i) {
        boolean flag = redisTemplate.opsForValue().setIfAbsent(lockKey, UUID.randomUUID().toString());
        redisTemplate.expire(lockKey, 5L, TimeUnit.MINUTES);
        return flag;
    }

    @Override
    protected boolean tryRelease(int i) {
        try {
            redisTemplate.delete(lockKey);
            return true;
        } catch (Exception e) {
            return false;
        }
    }
}
